<template>
  <div style="height: 100%">
    <MerakXTable
      ref="tableRef"
      v-bind="tablePayload"
      :query-columns="handleQueryColumns"
      :query-data="handleQueryData"
      :batch-click="handleBatchClick"
    >
      <template #handler="{ row }">
        <div style="display: flex">
          <el-button type="primary" v-auth="{ authArr: props.authArr, key: 'edit' }" link @click="saveEdit(row)">
            {{ $t("merak.edit") }}
          </el-button>
             <el-button type="primary" v-auth="{ authArr: props.authArr, key: 'edit' }" link @click="saveCopyEdit(row)">
            {{ $t("merak.copy") }}
          </el-button>
          <el-button type="danger" v-auth="{ authArr: props.authArr, key: 'del' }" link @click="delLine(row)">
            {{ $t("merak.delete") }}
          </el-button>
        </div>
      </template>
    </MerakXTable>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed,watch,getCurrentInstance } from "vue";
import MerakXTable, { MerakXTableInstance, MerakXTableColumn, MerakXTableQuery } from "@/components/MerakXTable";
import { getTariffHeadApi, getTariffListApi,getTariffBathDelApi } from "@/api/modules/goodsArchive/tariff/tariff";
import {typeObj} from "./tariffFormat";
import { ResultEnum } from "@/enums/httpEnum";
 import { useRouter } from "vue-router";
 import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";
 const { proxy } = getCurrentInstance() ?? {};
const router = useRouter();
const props = defineProps<{
  type: string;
  typeId: string;
  params:object;
  authArr:Array<T>;
}>();
console.log(props);

const saveEdit = rows => {
  $emit('editData',rows)
};
const saveCopyEdit=rows=>{
    $emit('editCopyData',rows)
}
const delLine=rows=>{
     $emit('delLine',rows)
}

//#region 列表

// 页面配置数据
let authArr = ref({});
const state = reactive<{
  org_id: string;
  key_words: string;
  columnType: Object;
}>({
  org_id: "",
  key_words: "",
  columnType: {}
});

// 动态计算表格的外部筛选数据

const params = computed(() => ({...{type_id: props.typeId },...props.params}));
const columnTypeNew = computed(() => {
  let column=['selection',{ type: 'handle', width: proxy.$t("lang") == 'zh' ? 150 : 250, slot: 'handler' }];
  if(!props.authArr?.del?.show && !props.authArr?.edit?.show){
    column=['selection']
  }
  return column;
});
const enabledExport=computed(() => (props.authArr?.export?.show));
// watch(()=>props.authArr,newVal=>{
// enabledExport.value=props.authArr?.export?.show;
// })
watch(()=>props.params,newVal=>{
  params.value={...{type_id: props.typeId },...props.params}
})

const tableHandler = computed(()=>{
  const  handlesMap = {
			moreEdit: {
				type: "moreEdit", text: "批量编辑"
			}, 
      moreDel:{ type: "moreDel", text: "批量删除",color:'red' }
      };
      if (props.authArr?.edit?.show == false) {
          delete handlesMap["moreEdit"];
        }
      if (props.authArr?.del?.show == false) {
			delete handlesMap["moreDel"];
		}
  return Object.values(handlesMap);
})
// 表格配置属性
const tablePayload = reactive<MerakXTableProps>({

  // 列设置存储的数据对照值
  columnsByStore: [],
  // 表格行数据的唯一 key, 跟后端同步
  rowKey: "id",//`tariff_${typeObj[props.typeId]}_id`,
  // 初始化的外部筛选数据
  params,

  //导出
  enabledExport: enabledExport,
  // 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
  columnType: columnTypeNew,
  // columnType: ['selection',{ type: 'handle', width: proxy.$t("lang") == 'zh' ? 120 : 220, slot: 'handler' }],
  // 批量操作选项
  batches:tableHandler,

  // 操作列选项
  // handles: [{ type: "delete", text: "删除", color: "red" }]
});


//  批量编辑
const openHrefUrl = router.resolve({
  //使用resolve
  name: "onlineMoreEditTariff", //这里是跳转页面的name
  path: `/goods/tariff/onlineMoreEditTariff` //这里是跳转页面的path地址
});
  const handleBatchClick: MerakXTableInstance["batchClick"] = async params => {

    if(params.type=="moreEdit"){
       window.open(openHrefUrl.href + `?tId=${props.typeId}&ids=${params.selectedKeys.join(",")}`, "", "width=1360,height=768");
    }
    if(params.type=="moreDel"){

        $emit('batchDelLine',params.selectedKeys)

      // getTariffBathDelApi
    }

}


//列表内容展示区
const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => {
  const params: Record<string, any> = {};
  if (!!page) {
    Object.assign(params, { ...page }, from);
  }
  return await getTariffListApi(params).then(res => {
    //  ========权限判断 start  ======
    // let authList = res?.auth_list;
    // if (authList) {
    // 	authArr.value = authList;
    // 	if (authList?.edit.show || authList?.del.show) {
    // 		state.columnType = { type: 'handle', width: proxy.$t("lang") == 'zh' ? 120 : 220, slot: 'handler' };
    // 	}
    // 	tablePayload.enabledExport = !!res?.auth_list?.export?.show;
    // }
    // ========权限判断 end  ======
    // 数据接口 start  ======
    if (res.code == ResultEnum.SUCCESS) {
      let data = res.data;

      const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };
      console.log(table_data);
      return table_data;
    }
  });
};

// 获取表头数据
const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
  // 初始化接口需要传入队列 loading 暴露的 id
  return getTariffHeadApi({ type_id: props.typeId }).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      // 克隆表头数据作为列设置的对照数据
      tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
      return {
        ...data,
        columns: [...data.columns].map(column => {
          switch (column.field) {
            	// 匹配列字段用于扩展自定义
            	case "hs_code_cn":
            	case "hs_code":
            		// 固定列
            		column.fixed = "left";
            		return column;
            default:
              return column;
          }
        })
      };
    }
  });
};
//#endregion

const $emit = defineEmits<{
  editData: any; //编辑
  delLine:any;//删除
  batchDelLine:any;//删除
  editCopyData:any
}>();
</script>
<style lang="scss" scoped></style>
